package com.haiyou.email.config;

import com.haiyou.common.util.RedisUtil;
import com.haiyou.email.properties.SpringEmailProperties;
import com.haiyou.email.service.SpringEmailService;
import com.haiyou.email.service.impl.SpringEmailServiceImpl;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.util.Properties;

/**
 * 自动配置
 */
@Configuration
@EnableConfigurationProperties(value = SpringEmailProperties.class)
@ConditionalOnProperty(prefix = SpringEmailProperties.PREFIX, name = "enable", havingValue = "true")
public class SpringEmailAutoConfiguration {

    @Bean
    public RedisUtil redisUtil(){
        return new RedisUtil();
    }

    /**
     * 配置模板文件
     *
     * @return
     */
    @Bean
    public FreeMarkerConfigurer configuration() {
        FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
        configurer.setTemplateLoaderPaths("classpath:/templates/");
        configurer.setDefaultEncoding("UTF-8");
        return configurer;
    }

    @Bean
    public JavaMailSender javaMailSender(SpringEmailProperties springEmailProperties) {

        //发邮件带附件,若附件名过长,会被截断
        //linux 会默认为 true，会截断附件名
        System.setProperty("mail.mime.splitlongparameters", "false");

        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(springEmailProperties.getHost());
        sender.setPort(springEmailProperties.getPort());
        sender.setUsername(springEmailProperties.getUsername());
        sender.setPassword(springEmailProperties.getPassword());
        sender.setDefaultEncoding("Utf-8");
        Properties p = new Properties();
        p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        p.setProperty("mail.smtp.socketFactory.port", springEmailProperties.getPort().toString());
        p.setProperty("mail.smtp.auth", "true");
        p.setProperty("mail.smtp.starttls.enable", "true");
        p.setProperty("mail.smtp.starttls.required", "true");
        sender.setJavaMailProperties(p);
        return sender;
    }

    @Bean
    public SpringEmailService springEmailService(SpringEmailProperties springEmailProperties) {
        return new SpringEmailServiceImpl(springEmailProperties,
                javaMailSender(springEmailProperties),
                configuration(),
                redisUtil());
    }

}
